package com.cssw.fyzb.tps.api.tf56pay;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.tps.api.yspay.utils.DateUtil;
import com.cssw.fyzb.tps.api.yspay.utils.StringUtils;
import com.cssw.fyzb.tps.config.tf56pay.TfpayConfig;
import com.cssw.fyzb.tps.third.tf56pay.util.HttpClient;
import com.cssw.fyzb.tps.third.tf56pay.util.ParamUtil;
import com.cssw.fyzb.tps.third.tf56pay.util.RSAUtils;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * @Author: yangyiqun
 * @Date: 2021/1/25 20:26
 */
@Function(description = "传化快捷支付签约查询", parameters = {
        @Parameter(name = "orderNo", type = Type.String, description = "业务流水号", required = true),
})
@Component
public class Tf56PayQuickSignQuery implements Action {

    private static final Logger logger = LoggerFactory.getLogger(Tf56PayQuickSignQuery.class);

    @Autowired
    private TfpayConfig tf56payConfig;

    @Override
    public Response execute(Request request) throws Exception {

        String businessnumber = request.getString("orderNo");

        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("appid", tf56payConfig.getAppid());
            map.put("tf_timestamp", DateUtil.getCurrentDate(DateUtil.dtLong));
            map.put("service_id", "tf56pay.gateway.signQuery");
            map.put("sign_type", tf56payConfig.getSignType());
            map.put("terminal", "PC");
            map.put("businessnumber", businessnumber);

            String url = tf56payConfig.getUrl();
            String pfxFileName = tf56payConfig.getPfxFileName();// enterprisetest.pfx

            String keyPassword = tf56payConfig.getKeyPassword();
            String originalMessage = ParamUtil.sortMapByKey(map);
            logger.info(originalMessage);
            byte[] signMessage = RSAUtils.signMessage(pfxFileName, keyPassword, originalMessage.getBytes());
            String signStr = new String(signMessage);
            map.put("tf_sign", signStr);
            logger.info(signStr);
            String result = HttpClient.sendHttpPost(url, map);
            logger.info("request:" + result);

            if (StringUtils.isBlank(result)) {
                return Response.fail("开通快捷支付失败");
            }

            return Response.success().put("data", JSON.parseObject(result));
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail("开通快捷支付失败");
        }
    }
}
